<template>
	<view>
		<!-- 使用 common-title 组件 -->
		<view class="title-bar">
			<common-title :title="pageTitle" :showBack="true"></common-title>

			<view class="news-publish">

				<view class="content">
					<!-- 基础用法，不包含校验规则 -->
					<uni-forms-item label="留言标题" required>
						<uni-easyinput placeholder="请输入留言标题" v-model="baseFormData.newsName" />
					</uni-forms-item>

					<uni-forms-item label="留言内容" required class="uni-forms-item-news-content-type">
						<uni-data-checkbox v-model="baseFormData.newsContentType" :localdata="newsContentTypeList" />
					</uni-forms-item>

					<view class="view-record-content" v-if="baseFormData.newsContentType=='voice_message'">

						<view class="view-record">
							<view class="circle" v-if="isStartRecordRef" :class="{ animate2: isStartRecordRef }"></view>
							<image :src="currentImage" class="img-record" :class="{ animate: isStartRecordRef }"
								@click="startOrStopRecord">
							</image>
						</view>
						<view class="v-record-text">{{recordTipsRef}}</view>
						<view class="v-record-path-ref">
							<view class="v-record-path">{{recordName}}</view>
							<view class="view-listener" @click="listenerRecord" v-if="recordPathRef">
								<image src="/static/icon_listener.png"></image>试听
							</view>
						</view>




					</view>
					<view class="news-text-content" v-else>

						<uni-forms-item label="">
							<uni-easyinput class="news-content-textarea" type="textarea"
								v-model="baseFormData.textContent" placeholder="请输入文字" maxlength="100" />
						</uni-forms-item>


						<view class="text-content-bottom" v-if="baseFormData.newsContentType=='text_to_voice'">
							<view class="view-clear" @click="clearText">
								<image src="/static/icon_clear.png"></image>清空
							</view>
							<view class="view-listener" @click="listenerText">
								<image src="/static/icon_listener.png"></image>试听
							</view>
						</view>
					</view>


					<uni-forms-item label="发起人" required class="news-bed-list">


						<uni-data-select v-model="publishedValue" :localdata="selectPublishList"
							@change="onSelectPublishedChange" placeholder="请选择发起人"
							class="select-type"></uni-data-select>



					</uni-forms-item>

					<view class="view-opreration">
						<view class="btn-close" @click="close">关闭</view>
						<view class="btn-save" @click="saveAndPublish()">发布</view>
					</view>
				</view>
			</view>
			<!-- <audio style="text-align: left" :src="current.src" 
				:author="current.author" :action="audioAction" controls></audio> -->

		</view>


		<!-- 右滑菜单，病床 -->
		<SelectBed ref="selectBedRef" v-model:showRight="showRight" v-model:checkBedList="checkBedList"></SelectBed>


	</view>
</template>


<script setup>
	import * as httpConfig from "../../common/http-config.js";
	import * as DataUtils from "../../utils/DataUtils";
	import CommonTitle from '@/components/common-title.vue';
	import SelectBed from '@/components/select-bed.vue';
	import * as UploadUtils from '../../utils/UploadUtils.js';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ref,
		onMounted,
		onUnmounted,
		computed,
		watch,
		defineComponent,
		getCurrentInstance,
		reactive
	} from 'vue'
	// 获取当前组件实例
	const instance = getCurrentInstance()
	// 定义响应式变量
	const initInfo = ref({})
	// 使用 onMounted 钩子
	onMounted(() => {
		console.log("组件已经挂载了.......")
		baseFormData.value.newsTipsDate = DataUtils.getCurrentDate2()
		// 暴露方法
		window["onFileUploaded"] = (jsonStr) => {
			let uploadRes = JSON.parse(jsonStr)
			realSaveAndPublish(uploadRes["fileUrl"])

		}
		// 暴露方法
		window["onDateTimeSelected"] = (jsonStr) => {
			let dateTimeRes = JSON.parse(jsonStr)
			baseFormData.value.newsTipsDate = dateTimeRes["dateTime"]
		}
		console.log("组件已经挂载了.......")
		if (instance?.proxy?.$globalData?.initInfo) {
			let jsonStr = instance.proxy.$globalData.initInfo;
			console.log("onMounted jsonStr = " + jsonStr)
			initInfo.value = JSON.parse(jsonStr)
			console.log("onMounted initInfo = " + initInfo.value)
			employeeList()
		}


	});

	onLoad((option) => {
		const orgId = option.orgId;
		console.log("orgId = " + orgId);
		if (!DataUtils.isEmpty(orgId)) {
			// 通过 options 获取参数
			initInfo.value["orgId"] = orgId
			employeeList()
		}

	})

	// 使用 onUnmounted 钩子
	onUnmounted(() => {
		console.log("组件移除了.......")
		stopRecord()

	});

	const pageTitle = ref("发布留言")
	const showRight = ref(false)


	const baseFormData = ref({
		newsName: "",
		newsType: "",
		newsContentType: "voice_message",
		textContent: "",
		newsTipsDate: ""

	})



	watch(
		() => baseFormData.value.newsContentType, // 监听 newsContentType
		(newValue, oldValue) => {
			// 在这里处理 newsContentType 变化后的逻辑
			recordPathRef.value = ""
			stopRecord()
		}
	);

	// 消息格式,text_message 文字消息，voice_message 语音消息，text_to_voice 文字转语音
	const newsContentTypeList = ref([{
		text: '语音消息',
		value: "voice_message"
	}, {
		text: '文字转语音消息', //3个字1S
		value: "text_to_voice"
	}, {
		text: '文字消息',
		value: "text_message"
	}])






	const clearText = () => {
		console.log("clearText")
		baseFormData.value.textContent = ""
	}
	const listenerText = () => {
		console.log("listenerText")
		if (DataUtils.isEmpty(baseFormData.value.textContent)) {
			uni.showToast({
				title: '请输入文字',
				icon: "error",
				duration: 2000
			});
			return
		}
		window.hb.ttsSpeak(baseFormData.value.textContent)
	}
	const listenerRecord = () => {
		console.log("listenerRecord")
		if (DataUtils.isEmpty(recordPathRef.value)) {
			return
		}
		window.hb.startFilePlay(recordPathRef.value)
	}

	// 选择发起人
	const publishedValue = ref(null)
	const selectPublishList = ref([])


	const onSelectPublishedChange = () => {
		console.log("onSelectPublishedChange " + publishedValue.value)


	}
	// 获取消息类型接口
	const employeeList = () => {
		let data = {
			"orgId": initInfo.value.orgId
		}
		uni.request({
			url: httpConfig.baseURL + httpConfig.employeeList, // 请求的 URL
			method: 'POST', // 请求方法为 POST
			data: data,

			success: (res) => {
				console.log('employeeList success');
				if (res.data.code == httpConfig.successCode) {
					selectPublishList.value = res.data.data.
					map(item => ({
						"value": item.employeeJn,
						"text": item.employeeName
					}))
				}
				// 在这里处理请求成功的情况
			},
			fail: (err) => {
				console.error('employeeList fail ');
			}
		});

	}

	const close = () => {
		console.log("close")
		uni.navigateBack(); // 例如：调用 UniApp 的返回上一页方法
	}



	const saveAndPublish = () => {
		console.log("saveAndPublish")
		if (DataUtils.isEmpty(baseFormData.value["newsName"])) {
			uni.showToast({
				title: '请填写留言标题',
				icon: "error",
				duration: 2000
			});
			return
		}
		// 语音消息
		if (baseFormData.value["newsContentType"] == "voice_message") {
			if (DataUtils.isEmpty(recordPathRef.value)) {
				uni.showToast({
					title: '请选择录音文件',
					icon: "error",
					duration: 2000
				});
				return
			}
		} else {
			if (DataUtils.isEmpty(baseFormData.value["textContent"])) {
				uni.showToast({
					title: '请输入文字内容',
					icon: "error",
					duration: 2000
				});
				return
			}

		}
		//语音消息，先上传文件
		if (baseFormData.value["newsContentType"] == "voice_message") {
			window.hb.uploadRecordFile(recordPathRef.value)
		} else {
			realSaveAndPublish()
		}

	}

	// 真正执行发布消息
	const realSaveAndPublish = (fileUrl) => {
		uni.showLoading({
			title: "正在保存"
		})
		let voiceDuration = 0
		if (baseFormData.value.newsContentType == "voice_message") {
			voiceDuration = currentTime.value
		} else if (baseFormData.value.newsContentType == "text_to_voice") {
			let contentLength = baseFormData.value.textContent.length;
			voiceDuration = Math.ceil(contentLength / 4.5); // 使用 Math.ceil 向上取整，确保不足 3 个字符的部分也算作 1 秒
		}
		console.log("realSaveAndPublish fileUrl = " + fileUrl)

		let data = {
			"name": baseFormData.value.newsName,
			"messageMethod": baseFormData.value.newsContentType,
			"textContent": baseFormData.value.textContent,
			"voiceFile": fileUrl,
			"recipientJn": publishedValue.value,

			"voiceDuration": voiceDuration
		}
		uni.request({
			url: httpConfig.baseURL + httpConfig.messageRecordSave, // 请求的 URL
			method: 'POST', // 请求方法为 POST
			data: data,
			success: (res) => {
				uni.hideLoading()
				if (res.data.code == httpConfig.successCode) {
					console.log('messageRecordSave success');
					uni.showToast({
						title: '保存成功',
						icon: "success",
						duration: 2000
					});
					uni.navigateBack(); // 例如：调用 UniApp 的返回上一页方法


				} else {
					uni.showToast({
						title: res.data.message,
						icon: "error",
						duration: 2000
					});
				}
				// 在这里处理请求成功的情况
			},
			fail: (err) => {
				uni.hideLoading()
				console.error('messageRecordSave fail ');
				uni.showToast({
					title: "保存失败:" + err,
					icon: "error",
					duration: 2000
				});
				// 在这里处理请求失败的情况
			}
		});

	}
	// 选择病床
	const selectBedList = () => {
		console.log("selectBedList")
		showRight.value = true

	}
	const closeDrawer = (e) => {
		console.log("closeDrawer")
		showRight.value = false
	}
	const change = (e, type) => {
		console.log((type === 'showLeft' ? '左窗口' : '右窗口') + (e ? '打开' : '关闭'));
	}
	const cancel = () => {
		console.log("cancel")
		closeDrawer()
	}
	const confirm = () => {
		console.log("confirm")
		closeDrawer()
	}
	var timer = null
	const currentTime = ref(0)
	const isStartRecordRef = ref(false)
	const startImage = ref("/static/image_record_start.png")
	const stopImage = ref("/static/image_record_end.png")
	const currentImage = ref("/static/image_record_end.png")
	const recordPathRef = ref("")
	const recordTipsRef = ref("请用手柄或靠近管理机后，点击话筒开始录音")
	const recordTime = ref(0)

	const recordName = computed(() => {
		// 使用 lastIndexOf 找到最后一个 "/" 的位置
		const lastSlashIndex = recordPathRef.value.lastIndexOf("/");
		if (lastSlashIndex !== -1) {
			// 使用 substring 截取最后一个 "/" 之后的部分
			return recordPathRef.value.substring(lastSlashIndex + 1);
		} else {
			return "";
		}

	});


	const startOrStopRecord = () => {
		console.log("startOrStopRecord")
		if (isStartRecordRef.value) {
			stopRecord()
		} else {
			startRecord()
		}

	}

	const startRecord = () => {
		if (isStartRecordRef.value) {
			return
		}
		console.log("startRecord")
		currentTime.value = 0
		recordPathRef.value = ""
		let status = window.hb.startRecord()
		if (status == "0") {
			uni.showToast({
				title: '开始录音成功',
				icon: "error",
				duration: 2000
			});
			currentImage.value = startImage.value
			isStartRecordRef.value = true;
			let timeStr = DataUtils.formatTime(currentTime.value)
			recordTipsRef.value = timeStr
			timer = setInterval(() => {
				currentTime.value = currentTime.value + 1
				let timeStr = DataUtils.formatTime(currentTime.value)
				recordTipsRef.value = timeStr
			}, 1000);


		} else {
			uni.showToast({
				title: '开始录音失败',
				icon: "error",
				duration: 2000
			});
		}


	}


	const stopRecord = () => {
		if (!isStartRecordRef.value) {
			return
		}
		recordTipsRef.value = "请用手柄或靠近管理机后，点击话筒开始录音"
		console.log("stopRecord")
		recordPathRef.value = ""
		currentImage.value = stopImage.value
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		let recordPath = window.hb.stopRecord()
		recordPathRef.value = recordPath
		if (DataUtils.isEmpty(recordPath)) {
			uni.showToast({
				title: '录音失败',
				icon: "error",
				duration: 2000
			});
		} else {
			uni.showToast({
				title: '停止录音成功',
				icon: "error",
				duration: 2000
			});
		}
		isStartRecordRef.value = false;
	}
	// 获取录音文件
	const getFileAsBase64 = async () => {
		console.log("getFileAsBase64")
		let base64 = window.hb.getFileAsBase64(recordPathRef.value)
		console.log("getFileAsBase64 base64 = " + base64)
		// 将 Base64 转换为 File 对象
		const file = base64ToFile(base64, recordName.value, "*/*");
		const tempFilePath = await saveFileToTemp(file);
		console.log("getFileAsBase64 file = " + tempFilePath)
	}

	function base64ToFile(base64, fileName, mimeType) {
		// 将 Base64 字符串解码为二进制数据
		const byteCharacters = atob(base64);
		const byteNumbers = new Array(byteCharacters.length);
		for (let i = 0; i < byteCharacters.length; i++) {
			byteNumbers[i] = byteCharacters.charCodeAt(i);
		}
		const byteArray = new Uint8Array(byteNumbers);

		// 创建 Blob 对象
		const blob = new Blob([byteArray], {
			type: mimeType
		});

		// 将 Blob 转换为 File 对象
		return new File([blob], fileName, {
			type: mimeType
		});
	}
</script>


<style lang="less" scoped>
	@vw: 8.015vw;
	@vh: 5.4vh;

	.news-publish {
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: center;

		.content {

			width: 500/@vw;

			color: #000000;

			// 消息类型
			.uni-forms-item-news_type {
				margin-top: 10/@vh;
			}

			// 消息内容类型
			.uni-forms-item-news-content-type {
				margin-top: 10/@vh;
			}

			.view-listener {
				display: flex;
				flex-direction: row;
				align-items: center;
				margin-right: 10/@vw;
				color: #0F6AF8;
				font-size: 13/@vh;

				image {
					width: 18/@vw;
					height: 18/@vw;
					margin-right: 9/@vw;
				}
			}

			// 录音按钮
			.view-record-content {

				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;

				.view-record {

					width: 96/@vw;
					height: 96/@vw;
					position: relative;

					.circle {
						width: 75/@vw;
						height: 75/@vw;
						border-radius: 40/@vw;
						background-color: #BAD4F1;
						position: absolute;
						top: 50%;
						/* 将图片的顶部定位到父容器的中心 */
						left: 50%;
						/* 将图片的左侧定位到父容器的中心 */
						transform: translate(-50%, -50%);
						/* 将图片向左和向上移动自身宽高的一半 */
					}

					.img-record {
						position: absolute;
						width: 75/@vw;
						height: 75/@vh;
						top: 50%;
						/* 将图片的顶部定位到父容器的中心 */
						left: 50%;
						/* 将图片的左侧定位到父容器的中心 */
						transform: translate(-50%, -50%);
						/* 将图片向左和向上移动自身宽高的一半 */

					}

				}

				.v-record-text {
					color: #586F93;
					font-size: 9/@vh;
				}

				.v-record-path-ref {
					display: flex;
					flex-direction: row;
					align-items: center;
					font-size: 13/vh;

					.v-record-path {
						margin-right: 10/@vw;
					}
				}
			}

			// 文字输入框
			.news-text-content {
				margin-top: 10/@vh;
				width: 100%;



				position: relative;

				.news-content-textarea {
					position: relative;

				}

				.text-content-bottom {

					position: absolute;
					top: 75/@vh;
					display: flex;
					justify-content: space-between;
					width: 100%;

					.view-clear {
						display: flex;
						flex-direction: row;
						align-items: center;
						margin-left: 100/@vw;
						color: #586F93;
						font-size: 13/@vh;

						image {
							width: 18/@vw;
							height: 18/@vw;
							margin-right: 9/@vw;
						}
					}






				}



			}

			// 选择时间
			.news-tips-date {
				margin-top: 20/@vh;
			}

			.news-bed-list {

				width: 100%;
				margin-top: 10/@vh;

				.view-bed-list {
					display: flex;
					flex-direction: row;
					align-items: center;
					background-color: white;
					border: 1px solid #dcdfe6;
					background-color: ;
					border-radius: 4px;
					color: #2C2E30;
					width: 100%;
					height: 34/@vh;
					white-space: nowrap;
					/* 强制文本一行显示 */
					overflow: hidden;
					text-overflow: ellipsis;
					font-size: 13/@vh;

					.view-bed-item {

						color: #2C2E30;
						font-size: 13/@vh;
					}

					text {
						margin-left: 8/@vw;
						color: #999;
					}

				}


			}

			// 底部操作按钮
			.view-opreration {
				width: 100%;
				justify-content: center;
				display: flex;
				flex-direction: row;
				font-size: 13/@vh;
				align-items: center;
				margin-top: 40/@vh;

				.btn-close {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 50/@vw;
					height: 28/@vh;
					border-radius: 3/@vh;
					border: 0.5/@vh solid #0F6AF8;
					color: #2C2E30;
				}

				.btn-save {
					margin-left: 32/@vw;
					display: flex;
					justify-content: center;
					align-items: center;
					width: 50/@vw;
					height: 28/@vh;
					border-radius: 3/@vh;
					background-color: #0F6AF8;
					color: white;
				}

				.btn-save-publish {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 50/@vw;
					height: 28/@vh;
					border-radius: 3/@vh;
					background-color: #0F6AF8;
					color: white;
				}
			}

		}

	}



	/* 定义动画 */
	.animate {
		animation: scaleAnimation 2s infinite;
	}

	@keyframes scaleAnimation {
		0% {
			transform: translate(-50%, -50%) scale(1);
			/* 保持居中并缩放 */
		}

		50% {
			transform: translate(-50%, -50%) scale(0.8);
			/* 保持居中并缩放 */
		}

		100% {
			transform: translate(-50%, -50%) scale(1);
			/* 保持居中并缩放 */
		}
	}

	/* 定义动画 */
	.animate2 {
		animation: scaleAndFade 1.5s infinite linear;
		/* linear 表示匀速 */
	}

	@keyframes scaleAndFade {
		0% {
			transform: translate(-50%, -50%) scale(1);
			/* 初始大小 */
			opacity: 1;
			/* 完全不透明 */
		}

		50% {
			transform: translate(-50%, -50%) scale(1.5);
			/* 放大到 1.2 倍 */
			opacity: 0.3;
			/* 半透明 */
		}

		100% {
			transform: translate(-50%, -50%) scale(1.2);
			/* 保持 1.2 倍 */
			opacity: 0;
			/* 完全透明 */
		}
	}



	::v-deep.uni-forms-item__label {
		color: #2C2E30;
		font-size: 13/@vh;
	}

	::v-deep.uni-data-checklist .checklist-group .checklist-box .checklist-content .checklist-text {
		font-size: 13/@vh;
		color: #2C2E30;
	}



	// 输入框
	::v-deep.uni-easyinput__content-input {

		height: 34/@vh;
		font-size: 13/@vh;
		color: #2C2E30;
	}

	::v-deep.uni-easyinput__placeholder-class {
		font-size: 13/@vh;

	}

	::v-deep.uni-select {
		height: 36/@vh;
		font-size: 13/@vh;
		color: #2C2E30;
	}

	::v-deep.uni-select__selector-item {
		font-size: 13/@vh !important;
	}

	::v-deep.uni-icons {
		font-size: 20/@vh !important;
	}

	::v-deep.uni-select__input-placeholder {
		font-size: 13/@vh !important;
		color: #999;
	}

	::v-deep.uni-forms-item__label {
		width: 90/@vw !important;
	}

	::v-deep.uni-forms-item {
		margin: 0;
		display: flex;
		flex-direction: row;
		align-items: center;

	}

	::v-deep.uni-easyinput__content-textarea {
		height: 90/@vh ;
		font-size: 13/@vh;
		color: #2C2E30;
		min-height: 0px;

	}

	::v-deep.uni-drawer__content {
		width: 340/@vw !important;
	}

	::v-deep.uni-select__input-placeholder {
		font-size: 13/@vh !important;
	}

	::v-deep.uni-date__x-input {
		font-size: 13/@vh !important;
		height: 34/@vh;
		line-height: 34/@vh;
	}

	::v-deep.uni-date-x {
		color: #2C2E30;
	}
</style>